<template>
  <div class="dashboard-container">
    <div class="dashboard-overlay">
      <el-row :gutter="20">
        <!-- 顶部指标卡片 -->
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="indicator-card">
            <div class="indicator-content">
              <div class="indicator-icon" style="background-color: #409eff">
                <i class="el-icon-user"></i>
              </div>
              <div class="indicator-text">
                <div class="indicator-title">读者数量</div>
                <div class="indicator-value">{{ basicInfo.readerCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="indicator-card">
            <div class="indicator-content">
              <div class="indicator-icon" style="background-color: #67c23a">
                <i class="el-icon-notebook-2"></i>
              </div>
              <div class="indicator-text">
                <div class="indicator-title">图书总量</div>
                <div class="indicator-value">{{ basicInfo.bookCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="indicator-card">
            <div class="indicator-content">
              <div class="indicator-icon" style="background-color: #e6a23c">
                <i class="el-icon-collection"></i>
              </div>
              <div class="indicator-text">
                <div class="indicator-title">在馆图书</div>
                <div class="indicator-value">{{ basicInfo.zaiGuanCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="indicator-card">
            <div class="indicator-content">
              <div class="indicator-icon" style="background-color: #f56c6c">
                <i class="el-icon-reading"></i>
              </div>
              <div class="indicator-text">
                <div class="indicator-title">借出图书</div>
                <div class="indicator-value">{{ basicInfo.rentCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="chart-row">
        <!-- 图书分类饼图 -->
        <el-col :xs="24" :sm="12">
          <el-card shadow="hover" class="chart-card">
            <div slot="header" class="chart-title">
              <span>图书分类分布</span>
            </div>
            <div class="chart-container">
              <pie-chart :chart-data="categoryData" />
            </div>
          </el-card>
        </el-col>

        <!-- 月度借阅柱状图 -->
        <el-col :xs="24" :sm="12">
          <el-card shadow="hover" class="chart-card">
            <div slot="header" class="chart-title">
              <span>月度借阅统计</span>
            </div>
            <div class="chart-container">
              <bar-chart :chart-data="monthlyBorrowData" />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="hot-books-row">
        <!-- 图书热榜 -->
        <el-col :span="24">
          <el-card shadow="hover" class="hot-books-card">
            <div slot="header" class="chart-title">
              <span>图书热榜</span>
              <el-radio-group
                v-model="hotBookType"
                size="mini"
                class="hot-book-switch"
              >
                <el-radio-button label="weekly">本周热榜</el-radio-button>
                <el-radio-button label="monthly">本月热榜</el-radio-button>
                <el-radio-button label="yearly">年度热榜</el-radio-button>
              </el-radio-group>
            </div>
            <div
              class="hot-books-container"
              ref="hotBooksContainer"
              @mouseenter="pauseScroll"
              @mouseleave="resumeScroll"
            >
              <div
                class="hot-book-list"
                :style="{ transform: 'translateY(' + currentOffset + 'px)' }"
              >
                <div
                  v-for="book in displayedHotBooks"
                  :key="book.key"
                  class="hot-book-item"
                  :class="{ top3: book.id <= 3 }"
                >
                  <div class="hot-book-rank">{{ book.id }}</div>
                  <div class="hot-book-cover">
                    <img :src="getSrc(book.coverUrl)" alt="封面" />
                  </div>
                  <div class="hot-book-info">
                    <div class="hot-book-title">{{ book.bookName }}</div>
                    <div class="hot-book-author">{{ book.author }}</div>
                    <div class="hot-book-count">借阅量: {{ book.count }}</div>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import BarChart from "../components/BarChart.vue";
import PieChart from "../components/PieChart.vue";
export default {
  data() {
    return {
      basicInfo: {
        readerCount: 0,
        bookCount: 0,
        zaiGuanCount: 0,
        rentCount: 0,
      },

      categoryData: [],
      monthlyBorrowData: {},
      hotBookType: "weekly",
      switchTimer: null,
      switchInterval: 60000, // 60秒切换一次
      hotBooks: [],
      scrollInterval: null,

      scrollPosition: 0,
      itemHeight: 130, // 每个条目的高度（根据实际样式调整）
      scrollSpeed: 0.4, // 滚动速度 ms
      visibleItemCount: 4, //一次性能看到多少条目
      isPaused: false,
      animationId: null,
    };
  },
  components: { BarChart, PieChart },
  computed: {
    displayedHotBooks() {
      // 计算当前应该显示哪些item
      const startIndex =
        Math.floor(this.scrollPosition / this.itemHeight) %
        this.hotBooks.length;
      let endIndex = startIndex + 1;
      if (this.hotBooks.length > 3) {
        endIndex = startIndex + this.visibleItemCount + 2; // +1作为缓冲
      }

      let result = [];
      for (let i = startIndex; i < endIndex; i++) {
        const index = i % this.hotBooks.length;
        result.push({
          ...this.hotBooks[index],
          key: `${this.hotBooks[index].id}_${i}`, // 确保key唯一
        });
      }

      return result;
    },
    currentOffset() {
      return -(this.scrollPosition % this.itemHeight);
    },
  },
  watch: {
    hotBookType() {
      this.hotBooks = [];
      this.getHot();
      this.resetScroll();
    },
  },
  created() {
    this.getBasicInfo();
    this.getCategoryData();
    this.getMonthlyBorrowData();
    this.getHot();
    if (this.hotBooks.length > 3) {
      this.startAutoSwitch();
    }
  },
  mounted() {
    if (this.hotBooks.length > 3) {
      this.startScroll();
    }
  },
  beforeDestroy() {
    this.stopScroll();
    this.stopAutoSwitch();
  },
  methods: {
    getSrc(coverUrl) {
      if (coverUrl) {
        return coverUrl;
      } else {
        return this.defaultCover;
      }
    },
    async getHot() {
      const params = {
        type: this.hotBookType,
      };
      const response = await this.$request.get("/api/dashboard/getHot", {
        params: params,
      });
      if (response.code == 200) {
        console.log("getHot", response.data);
        this.hotBooks = response.data;
      }
    },
    async getMonthlyBorrowData() {
      const response = await this.$request.get(
        "/api/dashboard/getCountGroupByMonth"
      );
      if (response.code == 200) {
        console.log("getMonthlyBorrowData", response.data);
        this.monthlyBorrowData = response.data;
      }
    },
    async getCategoryData() {
      const response = await this.$request.get(
        "/api/dashboard/getCountGroupByCategory"
      );
      if (response.code == 200) {
        console.log("getCategoryData", response.data);
        this.categoryData = response.data;
      }
    },
    async getBasicInfo() {
      const response = await this.$request.get("/api/dashboard/getBasicInfo");
      if (response.code == 200) {
        console.log("getBasicInfo", response.data);
        this.basicInfo.readerCount = response.data.readerCount;
        this.basicInfo.bookCount = response.data.bookCount;
        this.basicInfo.zaiGuanCount = response.data.zaiGuanCount;
        this.basicInfo.rentCount = response.data.rentCount;
      }
    },
    startAutoSwitch() {
      this.stopAutoSwitch();
      this.switchTimer = setInterval(() => {
        this.switchHotBookType();
      }, this.switchInterval);
    },

    stopAutoSwitch() {
      if (this.switchTimer) {
        clearInterval(this.switchTimer);
        this.switchTimer = null;
      }
    },

    switchHotBookType() {
      const types = ["weekly", "monthly", "yearly"];
      const currentIndex = types.indexOf(this.hotBookType);
      const nextIndex = (currentIndex + 1) % types.length;
      this.hotBookType = types[nextIndex];
      this.handleTypeChange();
    },

    handleTypeChange() {
      this.stopAutoSwitch();
      this.hotBooks = [];
      this.getHot();
      this.resetScroll();
      if (this.hotBooks.length > 3) {
        this.startAutoSwitch(); // 重新启动定时器
      }
    },
    startScroll() {
      this.stopScroll();
      this.isPaused = false;

      const animate = () => {
        if (this.isPaused) return;

        this.scrollPosition += this.scrollSpeed;

        // 当滚动距离超过总高度时，重置位置
        if (this.scrollPosition >= this.hotBooks.length * this.itemHeight) {
          this.scrollPosition = 0;
        }

        this.animationId = requestAnimationFrame(animate);
      };

      this.animationId = requestAnimationFrame(animate);
    },
    stopScroll() {
      if (this.animationId) {
        cancelAnimationFrame(this.animationId);
        this.animationId = null;
      }
    },
    resetScroll() {
      this.scrollPosition = 0;
      if (!this.isPaused) {
        this.startScroll();
      }
    },
    pauseScroll() {
      this.isPaused = true;
      this.stopScroll();
    },
    resumeScroll() {
      this.isPaused = false;
      this.startScroll();
      // if (!this.animationId) {
      //   this.startScroll();
      // }
    },
  },
};
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  /* padding: 20px; */
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: relative;
}

.dashboard-container .dashboard-overlay {
  position: relative;
  z-index: 1;
  background-color: rgba(0, 0, 50, 0.7);
  border-radius: 10px;
  padding: 20px;
}

.indicator-card {
  margin-bottom: 20px;
  border: none;
  background-color: rgba(255, 255, 255, 0.9);
}

.indicator-card .indicator-content {
  display: flex;
  align-items: center;
}

.indicator-card .indicator-content .indicator-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.indicator-card .indicator-content .indicator-icon i {
  font-size: 24px;
  color: white;
}

.indicator-card .indicator-content .indicator-text .indicator-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.indicator-card .indicator-content .indicator-text .indicator-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.chart-row {
  margin-top: 20px;
}

.chart-card {
  border: none;
  background-color: rgba(255, 255, 255, 0.9);
}

.chart-card .chart-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-card .chart-container {
  height: 300px;
}

.hot-books-row {
  margin-top: 20px;
}

.hot-books-card {
  border: none;
  background-color: rgba(255, 255, 255, 0.9);
}

.hot-books-card .chart-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hot-books-card .hot-book-switch {
  margin-left: 20px;
}
/* 修改关键CSS部分 */
.hot-books-container {
  height: 400px;
  overflow: hidden;
  position: relative;
  padding: 10px;
}

.hot-book-list {
  will-change: transform;
  position: absolute;
  width: calc(100% - 20px);
  left: 10px;
  /* transition: transform 0.0001s linear; 更平滑的过渡 */
}

.hot-book-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 5px;
  background-color: rgba(255, 255, 255, 0.7);
  margin-bottom: 10px;
  height: 120px; /* 必须与itemHeight一致 */
  box-sizing: border-box;
}

.hot-book-item:hover {
  background-color: rgba(64, 158, 255, 0.1);
  transform: translateX(5px);
}

.hot-book-item.top3 {
  background-color: rgba(64, 158, 255, 0.2);
}

.hot-book-item.top3 .hot-book-rank {
  color: #f56c6c;
  font-weight: bold;
}

.hot-book-item .hot-book-rank {
  width: 30px;
  text-align: center;
  font-size: 16px;
  color: #666;
}

.hot-book-item .hot-book-cover {
  width: 60px;
  height: 80px;
  margin: 0 15px;
}

.hot-book-item .hot-book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 3px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.hot-book-item .hot-book-info {
  flex: 1;
}

.hot-book-item .hot-book-info .hot-book-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.hot-book-item .hot-book-info .hot-book-author {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.hot-book-item .hot-book-info .hot-book-count {
  font-size: 14px;
  color: #409eff;
}
</style>